using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class LoadTexture
{
    // 图片路径（可以根据需要修改为绝对路径或相对路径）
    public string imagePath = "Assets/Textures/myImage.png"; // 示例路径
    public GameObject targetObject; // 需要贴图的目标物体

    // void Start()
    // {
    //     // 加载并应用纹理
    //     LoadAndApplyTexture(imagePath, targetObject);
    // }

    public static Dictionary<string, Texture2D> texture_dc = new Dictionary<string, Texture2D>();

    public static void LoadAndApplyTextureToObj3D(string path, GameObject obj, bool flip_x = false, bool flip_y = false,
        bool use_transparent_material = true, bool load_from_resources = false, bool use_cache = true)
    {
        if (obj == null)
        {
            Debug.LogError("Target object is null!");
            return;
        }

        string key = $"{path}_{flip_x}_{flip_y}";

        Texture2D texture = null;

        if (use_cache && texture_dc.ContainsKey(key))
        {
            texture = texture_dc[key];    
        }
        else
        {
            if (load_from_resources)
            {
                // 从 Resources 文件夹加载图片
                string resourcePath = Path.ChangeExtension(path, null); // 移除扩展名
                var original_texture = Resources.Load<Texture2D>(resourcePath);
                if (original_texture == null)
                {
                    Debug.LogError($"Failed to load texture from Resources at path: {resourcePath}");
                    return;
                }

                // 创建一个可读副本
                Texture2D readableTexture = new Texture2D(original_texture.width, original_texture.height, original_texture.format, original_texture.mipmapCount > 1);
                Graphics.CopyTexture(original_texture, readableTexture);
                texture = readableTexture;
            }
            else
            {
                // 从文件系统加载图片
                if (!File.Exists(path))
                {
                    Debug.LogError($"File not found at path: {path}");
                    return;
                }

                byte[] fileData = File.ReadAllBytes(path);
                texture = new Texture2D(2, 2); // 初始尺寸会自动调整
                if (!texture.LoadImage(fileData))
                {
                    Debug.LogError("Failed to load texture from image data.");
                    return;
                }
            }
            
            // 翻转纹理
            texture = FlipTexture(texture, flip_x: flip_x, flip_y: flip_y);
        }
        
        // 检查物体是否有材质并应用纹理
        Renderer renderer = obj.GetComponent<Renderer>();
        if (renderer != null)
        {
            // 为当前物体创建材质的副本
            Material material = new Material(Shader.Find("Standard"));
            // Material material = new Material(renderer.material);
            
            material.mainTexture = texture;
            
            // material.SetTexture("_Emission", texture);
            if (use_transparent_material)
            {
                if (material.IsKeywordEnabled("_ALPHAPREMULTIPLY_ON"))
                {                            
                    material.renderQueue = 3000;
                }
                material.SetFloat("_Mode", 3); // 使用透明模式
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                material.SetInt("_ZWrite", 0);
                material.DisableKeyword("_ALPHATEST_ON");
                material.EnableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = 3000;
            }
            
            renderer.material = material;
            
            // Debug.Log($"Object: {obj.name}, Material: {material.name}, Material.id: {material.GetInstanceID()}," +
            //           $" Shader.name: {material.shader.name}, Shader.ID: {material.shader.GetInstanceID()}");

            if (use_cache && !texture_dc.ContainsKey(key))
                texture_dc.Add(key, texture);
        }
        else
        {
            Debug.LogError("Target object does not have a Renderer component.");
        }
    }
    
    // 翻转纹理的 Y 轴
    static Texture2D FlipTexture(Texture2D original, bool flip_x = false, bool flip_y = false)
    {
        if (!(flip_x || flip_y))
            return original;

        int width = original.width;
        int height = original.height;

        // 创建一个新纹理
        Texture2D flipped = new Texture2D(width, height);
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                // // 将原始纹理的像素按照 Y 轴翻转
                // flipped.SetPixel(x, y, original.GetPixel(x, height - 1 - y));
                
                // 计算翻转后的像素位置
                int newX = flip_x ? width - 1 - x : x;
                int newY = flip_y ? height - 1 - y : y;

                // 设置像素
                flipped.SetPixel(x, y, original.GetPixel(newX, newY));
            }
        }
        flipped.Apply();
        return flipped;
    }
}